package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    private final SpecParamService paramService;

    public SpecGroupServiceImpl(SpecParamService paramService) {
        this.paramService = paramService;
    }

    @Override
    public List<SpecGroupDTO> querySpecList(Long categoryId) {
        // 查询规格组集合
        List<SpecGroup> groupList = query().eq("category_id", categoryId).list();
        // 转换为GroupDTO
        List<SpecGroupDTO> groupDTOList = SpecGroupDTO.convertEntityList(groupList);

        // 根据分类id查询所有的param
        List<SpecParamDTO> params = paramService.querySpecParams(categoryId, null, null);

        // 对params分组，param中的groupId一致的，放到一个组。然后用groupId作为key标记。形成Map
        Map<Long, List<SpecParamDTO>> map = params.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

/*        Map<Long, List<SpecParamDTO>> map = new HashMap<>();
        for (SpecParamDTO param : params) {
            if(!map.containsKey(param.getGroupId())){
                map.put(param.getGroupId(), new ArrayList<>());
            }
            map.get(param.getGroupId()).add(param);
        }*/

        // 遍历
        for (SpecGroupDTO groupDTO : groupDTOList) {
            groupDTO.setParams(map.get(groupDTO.getId()));
        }
        // 返回结果
        return groupDTOList;
    }
}